//
//  CertificateViewController.m
//  ForAddSDK
//
//  Created by liboxiang on 2018/1/18.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "CertificateViewController.h"
#import "DataHandler.h"

@interface CertificateViewController ()
@property (weak) IBOutlet NSPathControl *ownDev;
@property (weak) IBOutlet NSPathControl *ownDis;

@property (weak) IBOutlet NSPathControl *sdkDev;
@property (weak) IBOutlet NSPathControl *sdkDis;
@property (weak) IBOutlet NSPathControl *sdkAdhoc;

@property (weak) IBOutlet NSTextField *chineseName;
@property (weak) IBOutlet NSTextField *packageSvnPath;
@property (weak) IBOutlet NSTextField *bundleID;
@property (weak) IBOutlet NSTextField *gameVersion;

@property (weak) IBOutlet NSButton *confuseOCCheck;
@property (weak) IBOutlet NSButton *useiReSignCheck;
@property (weak) IBOutlet NSTextField *iReSignAppPath;

@property (weak) IBOutlet NSTextView *logTextView;
@end

@implementation CertificateViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    [self createFolder];
    [self setupOwnMobileprovision];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bundleIDAndGameVersionChange:) name:BundleIDAndGameVersionChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gameIDChange:) name:SelectedGameIDChangeNotification object:nil];
}

- (void)gameIDChange:(NSNotification *)notification {
    NSString *gameID = notification.object;
    if (![gameID isEqualToString:@"none"]) {
        NSDictionary *dic = [DataHandler getDefaultValuesWithGameID:gameID];
        if (dic) {
            _packageSvnPath.stringValue = dic[COLUMNID_PACK_SVN_PATH];
        }
    }
}

- (void)bundleIDAndGameVersionChange:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    if ([userInfo.allKeys containsObject:@"bundleID"]) {
        _bundleID.stringValue = userInfo[@"bundleID"];
    }
    if ([userInfo.allKeys containsObject:@"gameVersion"]) {
        _gameVersion.stringValue = userInfo[@"gameVersion"];
    }
}

- (void)createFolder
{
    [self folderPath];
}

- (void)setupOwnMobileprovision
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folderPath = [self folderPath];
    NSString *devPath = [folderPath stringByAppendingPathComponent:@"selfDev.mobileprovision"];
    BOOL isExist = [fileManager fileExistsAtPath:devPath];
    if (isExist) {
        _ownDev.stringValue = devPath;
    }
    
    NSString *disPath = [folderPath stringByAppendingPathComponent:@"selfDis.mobileprovision"];
    isExist = [fileManager fileExistsAtPath:disPath];
    if (isExist) {
        _ownDis.stringValue = disPath;
    }
}

- (NSString *)folderPath
{
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *folderPath = [docPath stringByAppendingPathComponent:@"ForAddSDK"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory;
    BOOL isExist = [fileManager fileExistsAtPath:folderPath isDirectory:&isDirectory];
    if (!isExist || !isDirectory) {
        [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return folderPath;
}

- (NSString *)mobileprovisionFolder
{
    NSString *folderPath = [self folderPath];
    NSString *mobileprovisionFolder = [folderPath stringByAppendingPathComponent:@"mobileprovisionDirectory"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory;
    BOOL isExist = [fileManager fileExistsAtPath:mobileprovisionFolder isDirectory:&isDirectory];
    if (!isExist || !isDirectory) {
        [fileManager createDirectoryAtPath:mobileprovisionFolder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return mobileprovisionFolder;
}

- (NSString *)createPlatformFolder
{
    NSString *folderPath = [self folderPath];
    NSString *platformFolder = [folderPath stringByAppendingPathComponent:[DataHandler shareInstance].workPlatform];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory;
    BOOL isExist = [fileManager fileExistsAtPath:platformFolder isDirectory:&isDirectory];
    if (!isExist || !isDirectory) {
        [fileManager createDirectoryAtPath:platformFolder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return platformFolder;
}

- (BOOL)copyConfusionFile {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folderPath = [self createPlatformFolder];
    
    NSString *confusionFolder = [folderPath stringByAppendingPathComponent:@"confusion"];
    BOOL isDirectory;
    BOOL isExistConfusionFolder = [fileManager fileExistsAtPath:confusionFolder isDirectory:&isDirectory];
    if (!isExistConfusionFolder || !isExistConfusionFolder) {
        [fileManager createDirectoryAtPath:confusionFolder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *confusionPlist = [folderPath stringByAppendingPathComponent:@"confusion/confusion.plist"];
    NSString *confusionRuby = [folderPath stringByAppendingPathComponent:@"confusion/confusion.rb"];
    BOOL isExistPlist = [fileManager fileExistsAtPath:confusionPlist];
    if (!isExistPlist) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"confusion" ofType:@"plist"];
        if (path.length) {
            _logTextView.string = [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[path,confusionPlist]];
        }
    }
    BOOL isExistRuby = [fileManager fileExistsAtPath:confusionRuby];
    if (!isExistRuby) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"confusion" ofType:@"rb"];
        if (path.length) {
            NSString *log = [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[path,confusionRuby]];
            _logTextView.string = [_logTextView.string stringByAppendingString:log];
        }
    }
    return ([fileManager fileExistsAtPath:confusionPlist] && [fileManager fileExistsAtPath:confusionRuby]);
}

- (NSString *)createResignFolder
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *folderPath = [self createPlatformFolder];
    
    NSString *resignFolder = [folderPath stringByAppendingPathComponent:@"iReSign"];
    BOOL isDirectory;
    BOOL isExistConfusionFolder = [fileManager fileExistsAtPath:resignFolder isDirectory:&isDirectory];
    if (!isExistConfusionFolder || !isExistConfusionFolder) {
        [fileManager createDirectoryAtPath:resignFolder withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return resignFolder;
}

- (IBAction)saveOwnMobileprovision:(id)sender {
    NSString *folderPath = [self folderPath];
    NSString *devLog;
    if (DEL_SPACE(_ownDev.URL.path).length) {
        devLog = [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[DEL_SPACE(_ownDev.URL.path),[folderPath stringByAppendingPathComponent:@"selfDev.mobileprovision"]]];
    }
    
    NSString *disLog;
    if (DEL_SPACE(_ownDis.URL.path).length) {
        disLog = [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[DEL_SPACE(_ownDis.URL.path),[folderPath stringByAppendingPathComponent:@"selfDis.mobileprovision"]]];
    }
    _logTextView.string = [NSString stringWithFormat:@"%@%@",devLog, disLog];
}

- (IBAction)clearSDKMobileprovision:(id)sender {
    _sdkDev.URL = nil;
    _sdkDis.URL = nil;
    _sdkAdhoc.URL = nil;
}

- (IBAction)setupOwnDev:(id)sender {
    DataHandler *handler = [DataHandler shareInstance];
    if (!handler.isPathOK || handler.workPlatform.length == 0) {
        _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
        return;
    }
    if (DEL_SPACE(_ownDev.URL.path).length) {
        NSString *xcodeProjPath = [NSString stringWithFormat:@"%@%@/proj.ios_appstore_%@/arpg.xcodeproj",handler.svnPath,handler.projectSubPath,handler.workPlatform];
        NSMutableArray *arguments = [NSMutableArray arrayWithObject:xcodeProjPath];
        [arguments addObject:DEL_SPACE(_ownDev.URL.path)];
        [arguments addObject:@"Developer"];
        _logTextView.string = [DataHandler runScript:@"configSigning" type:@"rb" launchPath:@"/usr/bin/ruby" arguments:arguments];
    }
    else {
        _logTextView.string = @"请放置描述文件";
    }
}
- (IBAction)setupOwnDis:(id)sender {
    DataHandler *handler = [DataHandler shareInstance];
    if (!handler.isPathOK || handler.workPlatform.length == 0) {
        _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
        return;
    }
    if (DEL_SPACE(_ownDis.URL.path).length) {
        NSString *xcodeProjPath = [NSString stringWithFormat:@"%@%@/proj.ios_appstore_%@/arpg.xcodeproj",handler.svnPath,handler.projectSubPath,handler.workPlatform];
        NSMutableArray *arguments = [NSMutableArray arrayWithObject:xcodeProjPath];
        [arguments addObject:DEL_SPACE(_ownDis.URL.path)];
        [arguments addObject:@"Distribution"];
        _logTextView.string = [DataHandler runScript:@"configSigning" type:@"rb" launchPath:@"/usr/bin/ruby" arguments:arguments];
    }
    else {
        _logTextView.string = @"请放置描述文件";
    }
}

- (IBAction)setupSdkDev:(id)sender {
    DataHandler *handler = [DataHandler shareInstance];
    if (!handler.isPathOK || handler.workPlatform.length == 0) {
        _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
        return;
    }
    if (DEL_SPACE(_sdkDev.URL.path).length) {
        NSString *xcodeProjPath = [NSString stringWithFormat:@"%@%@/proj.ios_appstore_%@/arpg.xcodeproj",handler.svnPath,handler.projectSubPath,handler.workPlatform];
        NSMutableArray *arguments = [NSMutableArray arrayWithObject:xcodeProjPath];
        [arguments addObject:DEL_SPACE(_sdkDev.URL.path)];
        [arguments addObject:@"Developer"];
        _logTextView.string = [DataHandler runScript:@"configSigning" type:@"rb" launchPath:@"/usr/bin/ruby" arguments:arguments];
    }
    else {
        _logTextView.string = @"请放置描述文件";
    }
}
- (IBAction)setupSdkDis:(id)sender {
    DataHandler *handler = [DataHandler shareInstance];
    if (!handler.isPathOK || handler.workPlatform.length == 0) {
        _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
        return;
    }
    if (DEL_SPACE(_sdkDis.URL.path).length) {
        NSString *xcodeProjPath = [NSString stringWithFormat:@"%@%@/proj.ios_appstore_%@/arpg.xcodeproj",handler.svnPath,handler.projectSubPath,handler.workPlatform];
        NSMutableArray *arguments = [NSMutableArray arrayWithObject:xcodeProjPath];
        [arguments addObject:DEL_SPACE(_sdkDis.URL.path)];
        [arguments addObject:@"Distribution"];
        _logTextView.string = [DataHandler runScript:@"configSigning" type:@"rb" launchPath:@"/usr/bin/ruby" arguments:arguments];
    }
    else {
        _logTextView.string = @"请放置描述文件";
    }
}

- (NSString *)copyMobileProvision:(NSPathControl *)pathControl fileName:(NSString *)fileName
{
    if (DEL_SPACE(pathControl.URL.path).length) {
        NSString *mobileprovisionDirectory = [self mobileprovisionFolder];
        return [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[DEL_SPACE(pathControl.URL.path),[mobileprovisionDirectory stringByAppendingPathComponent:fileName]]];
    }
    return @"";
}

- (NSString *)copyResignMobileProvision:(NSPathControl *)pathControl fileName:(NSString *)fileName
{
    if (DEL_SPACE(pathControl.URL.path).length) {
        NSString *mobileprovisionDirectory = [self createResignFolder];
        return [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[DEL_SPACE(pathControl.URL.path),[mobileprovisionDirectory stringByAppendingPathComponent:fileName]]];
    }
    return @"";
}

- (IBAction)createPlist:(id)sender {
    if (DEL_SPACE(_ownDis.URL.path).length == 0 && 
        DEL_SPACE(_sdkDis.URL.path).length == 0 && 
        DEL_SPACE(_sdkAdhoc.URL.path).length == 0) {
        _logTextView.string = @"请放置描述文件";
    }
    else if (DEL_SPACE(_chineseName.stringValue).length == 0 ||
             DEL_SPACE(_packageSvnPath.stringValue).length == 0 ||
             DEL_SPACE(_bundleID.stringValue).length == 0 ||
             DEL_SPACE(_gameVersion.stringValue).length == 0) {
        _logTextView.string = @"请补全必要信息";
    }
    else {
        NSString *removeLog = [DataHandler runScript:@"removeSpecifiSuffixFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[[self mobileprovisionFolder],@"mobileprovision"]];
        NSArray *mobilePrivisionFileName = @[@"channel_dis.mobileprovision", @"channel_adhoc.mobileprovision", @"self_dis.mobileprovision", @"channel_dev.mobileprovision"];
        NSMutableArray *pathControllersArray = [NSMutableArray arrayWithCapacity:0];
        [pathControllersArray addObject:_sdkDis];
        [pathControllersArray addObject:_sdkAdhoc];
        [pathControllersArray addObject:_ownDis];
        [pathControllersArray addObject:_sdkDev];
        
        NSInteger mobileProvisionCount = 0;
        for (NSPathControl *pathControlTmp in pathControllersArray) {
            if (DEL_SPACE(pathControlTmp.stringValue).length) {
                mobileProvisionCount++;
            }
        }
        
        [self createPlatformFolder];
        NSString *confuseOC = _confuseOCCheck.state == NSControlStateValueOn ? @"confuseOC" : @"";
        NSString *useiReSign = @"";
        if (mobileProvisionCount > 1 && _useiReSignCheck.state == NSControlStateValueOn) {
            useiReSign = @"useiReSign";
        }
        if (confuseOC.length) {
            [self copyConfusionFile];
        }
        
        NSPathControl *pathControl = nil;
        NSString *copyMobileProvisionLog = @"";
        if (useiReSign.length && DEL_SPACE(_iReSignAppPath.stringValue).length) {
            if (useiReSign.length) {
                if (DEL_SPACE(_iReSignAppPath.stringValue).length) {
                    NSString *resignFolderPath = [self createResignFolder];
                    BOOL getWithToPack = NO;
                    for (int i = 0; i < pathControllersArray.count; i++) {
                        pathControl = (NSPathControl *)pathControllersArray[i];
                        if (!getWithToPack && DEL_SPACE(pathControl.stringValue).length) {
                            getWithToPack = YES;
                            copyMobileProvisionLog = [copyMobileProvisionLog stringByAppendingString:[self copyMobileProvision:pathControl fileName:mobilePrivisionFileName[i]]];
                        }
                        else {
                            copyMobileProvisionLog = [copyMobileProvisionLog stringByAppendingString:[self copyResignMobileProvision:pathControl fileName:mobilePrivisionFileName[i]]];
                        }
                    }
                    
                    NSMutableArray *arguments = [NSMutableArray arrayWithObject:[resignFolderPath stringByAppendingPathComponent:@"resign.rb"]];
                    [arguments addObject:DEL_SPACE(_iReSignAppPath.stringValue)];
                    NSString *log = [DataHandler runScript:@"createResignRuby" type:@"rb" launchPath:@"/usr/bin/ruby" arguments:arguments];
                    copyMobileProvisionLog = [NSString stringWithFormat:@"%@%@",copyMobileProvisionLog,log];
                }
                else {
                    _logTextView.string = @"请填写iReSign软件路径";
                    return;
                }
            }
        }
        else {
            for (int i = 0; i < pathControllersArray.count; i++) {
                pathControl = (NSPathControl *)pathControllersArray[i];
                copyMobileProvisionLog = [copyMobileProvisionLog stringByAppendingString:[self copyMobileProvision:pathControl fileName:mobilePrivisionFileName[i]]];
            }
        }
        
        DataHandler *handler = [DataHandler shareInstance];
        NSMutableArray *arg = [NSMutableArray arrayWithObject:[NSString stringWithFormat:@"%@/frameworks/runtime-src/",DEL_SPACE(_packageSvnPath.stringValue)]];
        [arg addObject:handler.workPlatform];
        [arg addObject:DEL_SPACE(_bundleID.stringValue)];
        [arg addObject:DEL_SPACE(_chineseName.stringValue)];
        [arg addObject:DEL_SPACE(_gameVersion.stringValue)];
        [arg addObject:[self folderPath]];
        [arg addObject:confuseOC];
        [arg addObject:useiReSign];
        [arg addObject:[NSString stringWithFormat:@"%ld",mobileProvisionCount]];
        [arg addObject:handler.targetName];
        NSString *runScriptLog = [DataHandler runScript:@"createPlistPython" type:@"py" launchPath:@"/usr/bin/python" arguments:arg];
        _logTextView.string = [NSString stringWithFormat:@"%@%@%@",removeLog,copyMobileProvisionLog,runScriptLog];
    }
}
@end
